package com.iakuil.app.common.core.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.iakuil.app.common.core.DictEnum;

import java.io.IOException;

/**
 * 字典枚举JSON序列化
 *
 * <p>为字典枚举在JSON中增加一个Label描述字段。
 *
 * @author Kai
 */
public class DictEnumSerializer extends JsonSerializer<DictEnum> {

    public static final DictEnumSerializer instance = new DictEnumSerializer();

    @Override
    public void serialize(DictEnum value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (value == null) {
            jsonGenerator.writeNull();
        } else {
            jsonGenerator.writeObject(value.getValue());
            jsonGenerator.writeFieldName(jsonGenerator.getOutputContext().getCurrentName() + "Label");
            jsonGenerator.writeString(value.getLabel());
        }
    }

    @Override
    @SuppressWarnings("rawtypes")
    public Class<DictEnum> handledType() {
        return DictEnum.class;
    }
}
